package com.happy3w.ssp.schoolmatehome.controller;

import com.happy3w.ssp.schoolmatehome.interceptor.AttributeKeys;
import com.happy3w.ssp.schoolmatehome.service.auth.TheUserDetail;
import com.happy3w.ssp.schoolmatehome.service.note.NoteDetail;
import com.happy3w.ssp.schoolmatehome.service.note.NoteSearcher;
import com.happy3w.ssp.schoolmatehome.service.note.NoteService;
import com.happy3w.ssp.schoolmatehome.service.note.NoteSummary;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RequiredArgsConstructor
@RestController
@RequestMapping("/api/me/template")
@PreAuthorize("hasRole('ROLE_NAMED')")
public class MeTemplateController {
    private final NoteService noteService;
    private final NoteSearcher noteSearcher;

    @GetMapping()
    public List<NoteSummary> findAll(
            @RequestAttribute(AttributeKeys.USER_DETAIL) TheUserDetail userDetail,
            @RequestParam(required = false, name = "query") String query,
            @RequestParam(required = false, name = "page", defaultValue = "0") int page,
            @RequestParam(required = false, name = "size", defaultValue = "20") int size) {
        return noteSearcher.findAllNoteTemplate(userDetail.getUser(), query, page, size);
    }

    @PostMapping()
    public void newTemplate(@RequestBody NewTemplateReq req,
                            @RequestAttribute(AttributeKeys.USER_DETAIL) TheUserDetail userDetail) {
        noteService.markTemplate(req.id, userDetail.getUser());
    }
    @Getter
    @Setter
    public static class NewTemplateReq {
        private Long id;
    }

    @DeleteMapping("/{id}")
    public void unmark(@PathVariable Long id,
                       @RequestAttribute(AttributeKeys.USER_DETAIL) TheUserDetail userDetail) {
        noteService.unmarkTemplate(id, userDetail.getUser());
    }

    @GetMapping("/{id}")
    public ResponseEntity<NoteDetail> findById(@PathVariable Long id,
                                               @RequestAttribute(AttributeKeys.USER_DETAIL) TheUserDetail userDetail) {
        Optional<NoteDetail> noteOpt = noteService.findById(id, userDetail.getUser());
        return noteOpt.map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }
}
